package org.black.phoneUtility.sms.schedule.app.fragment;

import org.black.phoneUtility.PhoneUtilityConstant;
import org.black.phoneUtility.R;
import org.black.phoneUtility.sms.reply.app.service.SmsReplyScheduleNotifyNotificationInentService;
import org.black.phoneUtility.sms.schedule.app.activity.SmsScheduleAddEditFragmentActivity;
import org.black.phoneUtility.sms.schedule.provider.SmsScheduleContract;
import org.black.phoneUtility.sms.schedule.widget.SmsScheduleListCursorAdapter;
import org.black.phoneUtility.util.admob.AdmobConstant;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.MultiChoiceModeListener;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class SmsScheduleListFragment extends Fragment implements
		LoaderCallbacks<Cursor>, MultiChoiceModeListener,
		AdapterView.OnItemClickListener {
	public static final String TAG = SmsScheduleListFragment.class.getName();
	private static final String LOG_TAG = SmsScheduleListFragment.class
			.getName();
	private ListView smsScheduleList;
	private SmsScheduleListCursorAdapter smsScheduleListCursorAdapter;
	private AlertDialog.Builder forAskingDeleteSmsSchedulesBuilder = null;
	private AlertDialog.Builder forAskingDeleteAllRecordsBuilder = null;
	private Activity activity;

	private int numberChoose = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setHasOptionsMenu(true);
		forAskingDeleteSmsSchedulesBuilder = new AlertDialog.Builder(
				getActivity());
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		this.smsScheduleListCursorAdapter = new SmsScheduleListCursorAdapter(
				activity, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		this.smsScheduleList.setAdapter(smsScheduleListCursorAdapter);
		this.smsScheduleListCursorAdapter.notifyDataSetChanged();
		activity.getLoaderManager().initLoader(
				PhoneUtilityConstant.INIT_LOADER_SMS_SCHEDULE_ID, null, this);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View result = inflater.inflate(R.layout.sms_schedule_list, container,
				false);

		this.activity = getActivity();

		this.smsScheduleList = (ListView) result
				.findViewById(R.id.smsScheduleListView);
		TextView emptyTextView = (TextView) result
				.findViewById(R.id.smsScheduleListViewNoDataTextView);
		emptyTextView
				.setText(getString(R.string.sms_schedule_list_no_data_tap_vertical_and_horizontal_above_to_add_a_reply_setting_to_this_list));
		this.smsScheduleList.setEmptyView(emptyTextView);
		this.smsScheduleList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
		this.smsScheduleList.setMultiChoiceModeListener(this);
		this.smsScheduleList.setOnItemClickListener(this);
		this.forAskingDeleteAllRecordsBuilder = new AlertDialog.Builder(
				getActivity());
		this.forAskingDeleteAllRecordsBuilder
				.setMessage(R.string.sms_schedule_list_do_you_really_want_to_clear_all_settings);
		this.forAskingDeleteAllRecordsBuilder.setPositiveButton(
				android.R.string.ok, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						getActivity().getContentResolver().delete(
								SmsScheduleContract.SmsSchedules.CONTENT_URI,
								null, null);
						Log.i(LOG_TAG, "Delete all sms schedule records");
					}
				}).setNegativeButton(android.R.string.cancel,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

					}

				});

		AdView adView = new AdView(activity);
		adView.setAdSize(AdSize.SMART_BANNER);
		adView.setAdUnitId(AdmobConstant.UNIT_ID);
		AdRequest adRequest = new AdRequest.Builder().build();
		adView.loadAd(adRequest);

		LinearLayout adViewLayout = (LinearLayout) result
				.findViewById(R.id.adViewLayout);
		adViewLayout.addView(adView);
		return result;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		inflater.inflate(R.menu.sms_schedule_list_actions, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			getActivity().onBackPressed();
			return false;
		case R.id.menu_sms_schedule_list_add:
			Intent intent = new Intent(getActivity(),
					SmsScheduleAddEditFragmentActivity.class);
			Bundle bundle = new Bundle();

			intent.putExtras(bundle);
			startActivity(intent);
			return true;
		case R.id.menu_sms_schedule_list_clear_all:
			this.forAskingDeleteAllRecordsBuilder.show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		return new CursorLoader(getActivity(),
				SmsScheduleContract.SmsSchedules.CONTENT_URI, null, null, null,
				null);
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
		if (data != null) {
			data.moveToFirst();
			if (smsScheduleListCursorAdapter != null) {
				smsScheduleListCursorAdapter.swapCursor(data);
				smsScheduleListCursorAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		if (smsScheduleListCursorAdapter != null) {
			smsScheduleListCursorAdapter.swapCursor(null);
		}
	}

	@Override
	public boolean onActionItemClicked(final ActionMode mode, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_sms_schedule_list_choose_multi_items_delete:
			forAskingDeleteSmsSchedulesBuilder
					.setMessage(getString(
							R.string.sms_reply_list_dialog_message_do_you_really_want_to_delete_numbers_settings,
							String.valueOf(numberChoose)));
			forAskingDeleteSmsSchedulesBuilder.setPositiveButton(
					android.R.string.ok, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							numberChoose = 0;
							smsScheduleListCursorAdapter.removeSelections();
							mode.finish();

							Intent scheduleNotifyNotificationServiceIntent = new Intent(
									activity,
									SmsReplyScheduleNotifyNotificationInentService.class);
							Bundle argumentsForSchedule = new Bundle();
							argumentsForSchedule
									.putInt(SmsReplyScheduleNotifyNotificationInentService.ARGUMENTS_ACTION_TYPE,
											SmsReplyScheduleNotifyNotificationInentService.ACTION_TYPE_RECHECK);
							scheduleNotifyNotificationServiceIntent
									.putExtras(argumentsForSchedule);
							activity.startService(scheduleNotifyNotificationServiceIntent);
							Log.d(LOG_TAG,
									"Start SmsReplyScheduleNotifyNotificationInentService!");
						}
					}).setNegativeButton(android.R.string.cancel,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});

			forAskingDeleteSmsSchedulesBuilder.show();
			return true;
		case R.id.menu_sms_schedule_list_choose_multi_items_copy:
			smsScheduleListCursorAdapter.copy();
			numberChoose = 0;
			mode.finish();
			return true;
		}
		return false;
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		this.activity = null;
		this.forAskingDeleteAllRecordsBuilder = null;
		this.forAskingDeleteSmsSchedulesBuilder = null;
		this.smsScheduleList = null;
		this.smsScheduleListCursorAdapter = null;
	}

	@Override
	public boolean onCreateActionMode(ActionMode mode, Menu menu) {
		numberChoose = 0;
		MenuInflater inflater = activity.getMenuInflater();
		inflater.inflate(R.menu.sms_schedule_list_choose_multi_items, menu);
		return true;
	}

	@Override
	public void onDestroyActionMode(ActionMode mode) {
		smsScheduleListCursorAdapter.clearSelection();

	}

	@Override
	public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
		MenuItem copyItem = menu
				.findItem(R.id.menu_sms_schedule_list_choose_multi_items_copy);
		if (numberChoose > 1) {
			copyItem.setVisible(false);
		} else {
			copyItem.setVisible(true);
		}
		return true;
	}

	@Override
	public void onItemCheckedStateChanged(ActionMode mode, int position,
			long id, boolean checked) {
		if (checked) {
			numberChoose++;
			smsScheduleListCursorAdapter.addSelection(position, checked);
		} else {
			numberChoose--;
			smsScheduleListCursorAdapter.removeSelection(position);
		}
		mode.setTitle(String.valueOf(numberChoose));
		mode.invalidate();

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent = new Intent(activity,
				SmsScheduleAddEditFragmentActivity.class);
		Bundle bundle = new Bundle();
		bundle.putLong(
				SmsScheduleAddEditFragmentActivity.ARGUMENTS_SMS_SCHEDULE_ID,
				id);
		intent.putExtras(bundle);
		startActivity(intent);
	}
}
